﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;

namespace Zatify.API.Controllers
{
    public class PromotionController : BaseController
    {
        public string Add(string token)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Promotion_Add",
                    new string[] { "Token" }, new object[] { token });

                switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                {
                    case 1:
                        return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
                    case -1:
                        return CommonLib.ErrorXml("Credit card info missing or incomplete", "6").ToString();
                    case -2:
                        return CommonLib.ErrorXml("Credit card is out of date", "7").ToString();
                    case -3:
                        return CommonLib.ErrorXml("Business has no coordinates", "8").ToString();
                    default:
                        return CommonLib.ErrorXml("Invalid token", "1").ToString();
                }
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string AddCategories(string token, int promotionid, string categories)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_PromotionCategory_Add",
                    new string[] { "Token", "PromotionId", "Categories" }, new object[] { token, promotionid, categories });

                switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                {
                    case 1:
                        return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["PromotionId"].ToString() }).ToString();
                    case -1:
                        return CommonLib.ErrorXml("Promotion not found", "2").ToString();
                    default:
                        return CommonLib.ErrorXml("Invalid token", "1").ToString();
                }
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }

        }

        public string UpdateProximityRadius(string token, int promotionId, int proximityRadiusId, int? customRange,
            bool over200MilesFlag = false, bool registeredOutsideOfZip = false, bool registeredOutsideOfState = false, bool registeredOutsideOfCity = false)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Promotion_ProximityRadius_Update",
                    new string[] { "Token", "PromotionId", "ProximityRadiusId", "CustomRange", "Over200MilesFlag", "RegisteredOutsideOfZip", "RegisteredOutsideOfState", "RegisteredOutsideOfCity" },
                    new object[] { token, promotionId, proximityRadiusId, customRange, over200MilesFlag, registeredOutsideOfZip, registeredOutsideOfState, registeredOutsideOfCity });

                switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                {
                    case 1:
                        return CommonLib.OkXml().ToString();
                    case -1:
                        return CommonLib.ErrorXml("Promotion not found", "2").ToString();
                    default:
                        return CommonLib.ErrorXml("Invalid token", "1").ToString();
                }
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string UpdateBaseCostTiming(string token, int promotionId, int baseCostTimingId, DateTime? baseCostTimingScheduledAt,
            DateTime? baseCostTimingStarts, DateTime? baseCostTimingEnds, DateTime? baseCostTimingStartsWithinDay, DateTime? baseCostTimingEndsWithinDay)
        {
            try
            {
                if (baseCostTimingStarts.HasValue && baseCostTimingEnds.HasValue)
                {
                    if (baseCostTimingStarts.Value.Date == baseCostTimingEnds.Value.Date)
                    {
                        baseCostTimingStarts = baseCostTimingStarts.Value.Date;
                        baseCostTimingEnds = baseCostTimingEnds.Value.Date.AddMinutes(59).AddSeconds(59);
                    }
                }

                if (baseCostTimingStarts.HasValue)
                {
                    baseCostTimingStarts = baseCostTimingStarts.Value.Date;

                    if (baseCostTimingStartsWithinDay.HasValue)
                    {
                        baseCostTimingStarts = baseCostTimingStarts.Value.Add(baseCostTimingStartsWithinDay.Value.TimeOfDay);
                    }
                }

                if (baseCostTimingEnds.HasValue)
                {
                    baseCostTimingEnds = baseCostTimingEnds.Value.Date;

                    if (baseCostTimingEndsWithinDay.HasValue)
                    {
                        baseCostTimingEnds = baseCostTimingEnds.Value.Add(baseCostTimingEndsWithinDay.Value.TimeOfDay);
                    }
                    else
                    {
                        baseCostTimingEnds = baseCostTimingEnds.Value.Date.AddMinutes(59).AddSeconds(59);
                    }
                }

                DataTable dt = DataAccess.GetDataTable("spAPI_Promotion_BaseCostTiming_Update",
                    new string[] { "Token", "PromotionId", "BaseCostTimingId", "BaseCostTimingScheduledAt", "BaseCostTimingStarts", "BaseCostTimingEnds", "BaseCostTimingStartsWithinDay", "BaseCostTimingEndsWithinDay" },
                    new object[] { token, promotionId, baseCostTimingId, baseCostTimingScheduledAt, baseCostTimingStarts, baseCostTimingEnds, baseCostTimingStartsWithinDay, baseCostTimingEndsWithinDay });

                switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                {
                    case 1:
                        return CommonLib.OkXml().ToString();
                    case -1:
                        return CommonLib.ErrorXml("Promotion not found", "2").ToString();
                    default:
                        return CommonLib.ErrorXml("Invalid token", "1").ToString();
                }
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string UpdateBudget(string token, int promotionId, decimal campaignBudget, string name, string promotionText)
        {
            try
            {
                List<string> paramName = new List<string>();
                List<object> paramValue = new List<object>();

                paramName.Add("Token");
                paramValue.Add(token);
                paramName.Add("PromotionId");
                paramValue.Add(promotionId);
                paramName.Add("CampaignBudget");
                paramValue.Add(campaignBudget);
                paramName.Add("Name");
                paramValue.Add(name);
                paramName.Add("PromotionText");
                paramValue.Add(promotionText);

                if (Request.ContentLength > 0)
                {
                    paramName.Add("PictureContentType");
                    paramValue.Add(Request.ContentType);

                    paramName.Add("Picture");
                    paramValue.Add(Request.BinaryRead(Request.ContentLength));
                }

                DataTable dt = DataAccess.GetDataTable("spAPI_Promotion_BudgetUpdate", paramName.ToArray(), paramValue.ToArray());

                switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                {
                    case 1:
                        return CommonLib.OkXml().ToString();
                    case -1:
                        return CommonLib.ErrorXml("Promotion not found", "2").ToString();
                    default:
                        return CommonLib.ErrorXml("Invalid token", "1").ToString();
                }
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string TestPay()
        {
            string payMessage = "";
            if (!PaymentService.Pay("4222222222222", "",
                                    new DateTime(2014, 10, 1), 10,
                                    "", out payMessage))
                return payMessage;
            else
                return "Paid";
        }

        public string Submit(string token, int promotionId, bool singleUseOnly = false, string match = "ALL")
        {
            try
            {
                decimal summaFromRest;
                decimal summaForPay;

                // try for pay
                string result = CommonLib.PayPromotion(token, promotionId, -1, out summaForPay, out summaFromRest);
                if (!string.IsNullOrEmpty(result))
                    return result;
                
                DataTable dt = DataAccess.GetDataTable("spAPI_Promotion_Submit",
                    new string[] { "Token", "PromotionId", "SummaPay", "SummaRest", "SingleUseOnly", "Match" },
                    new object[] { token, promotionId, summaForPay, summaFromRest, singleUseOnly, match });

                switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                {
                    case 1:
                        return CommonLib.OkXml().ToString();
                    case -1:
                        return CommonLib.ErrorXml("Promotion not found", "2").ToString();
                    case -2:
                        return CommonLib.ErrorXml("No categories specified", "3").ToString();
                    default:
                        return CommonLib.ErrorXml("Invalid token", "1").ToString();
                }
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string Stop(string token, int promotionId)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Promotion_Stop",
                    new string[] { "Token", "PromotionId" },
                    new object[] { token, promotionId });

                switch (Convert.ToInt32(dt.Rows[0]["IdResult"]))
                {
                    case 1:
                        return CommonLib.OkXml().ToString();
                    case -1:
                        return CommonLib.ErrorXml("Promotion not found", "2").ToString();
                    default:
                        return CommonLib.ErrorXml("Invalid token", "1").ToString();
                }
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public string Checkin(string token, int? promotionId, int? businessId, string code)
        {
            try
            {
                int resultId = -1;

                if (promotionId != null)
                {
                    DataTable dt = DataAccess.GetDataTable("spAPI_Promotion_Checkin",
                        new string[] { "Token", "PromotionId", "Code" },
                        new object[] { token, promotionId, code });

                    resultId = Convert.ToInt32(dt.Rows[0]["IdResult"]);
                }
                else if (businessId != null)
                {
                    DataTable dt = DataAccess.GetDataTable("spAPI_Promotion_Checkin",
                        new string[] { "Token", "BusinessId", "Code" },
                        new object[] { token, businessId, code });

                    resultId = Convert.ToInt32(dt.Rows[0]["IdResult"]);
                }

                switch (resultId)
                {
                    case 1:
                        return CommonLib.OkXml().ToString();
                    case -1:
                        return CommonLib.ErrorXml("Promotion code not found", "2").ToString();
                    default:
                        return CommonLib.ErrorXml("Invalid token", "1").ToString();
                }
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }

        public ActionResult GetPicture(string token, int promotionId)
        {
            if (!CommonLib.CheckToken(token))
            {
                return null;
            }

            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_Promotion_GetPicture",
                    new string[] { "Token", "PromotionId" }, new object[] { token, promotionId });
                return this.Image((byte[])dt.Rows[0]["Picture"], dt.Rows[0]["PictureContentType"].ToString());
            }
            catch { return null; }
        }

        public string GetReviews(string token, int promotionId)
        {
            try
            {
                DataTable dt = DataAccess.GetDataTable("spAPI_PromotionReview_GetList",
                    new string[] { "Token", "PromotionId" }, new object[] { token, promotionId });

                if (Convert.ToInt32(dt.Rows[0]["IdResult"]) == 0)
                    return CommonLib.ErrorXml("Invalid token", "1").ToString();
                else
                    return CommonLib.OkXml(new string[] { "Data" }, new string[] { dt.Rows[0]["Result"].ToString() }).ToString();
            }
            catch (Exception ex)
            {
                return CommonLib.ErrorXml(ex.Message, "100").ToString();
            }
        }
    }
}
